package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.util.List;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/dish")
public class DishController {
    //注入DishService
    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;

    /**
     * 保存菜品
     * 一级路径是dish，没有二级路径，请求方式是Post，参数是JSON格式的参数
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        log.info("保存菜品....{}", dishDto.getName());
//        dishService.save(dish);//dish表中没有flavor的集合，所以，这里的操作有问题
        dishService.saveDishAndFlavors(dishDto);//这个自定义的方法，需要在service层完成保持菜品和口味的操作
        return R.success("保存菜品成功");
    }

    @GetMapping("/list")
    public R<List<Dish>> list(Dish dish){
        return null;
    }





    /**
     * 菜品分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page<DishDto>> page(Integer page, Integer pageSize, String name) {
        //1. 创建分页对象
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        //创建DishDto的分页对象
        Page<DishDto> pageInfoDto = new Page<>(page, pageSize);
        //2. 创建普通查询对象
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //2.1 添加条件 select * from dish where name like ? order by 创建时间
        queryWrapper.like(StringUtils.isNotEmpty(name), Dish::getName, name);
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        //3. 执行分页查询
        dishService.page(pageInfo, queryWrapper);
        BeanUtils.copyProperties(pageInfo, pageInfoDto, "records");
        List<DishDto> dtoList = pageInfo.getRecords().stream().map((dish) -> {
            //把dish中的属性copy到dishDto对象
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish, dishDto);
            //dishDto中的categoryName属性单独设置值
            Long categoryId = dish.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                dishDto.setCategoryName(category.getName());
            }
            return dishDto;
        }).collect(Collectors.toList());
        pageInfoDto.setRecords(dtoList);
        return R.success(pageInfoDto);
    }
}
